load ("../src/Base.js");
var UnitTest = Base.extend({
	eq: function (a, b) {
		if (a !== b) {
			console.log("Error: Values " + a + " and " + b + " are not equal");
			throw new Error("Stopped on failure");
		}
	},
	eqList: function (a, b) {
		if (a.length == b.length) {
			for (var i = 0; i < a.length; i++) {
				if (a[i] != b[i]) {
					console.log("Error: lists " + a + " and " + b + " have different values");							
					throw new Error("Stopped on failure");
				}
			}
			return;
		}

		console.log("Error: lists " + a + " and " + b + " have different lengths");
		throw new Error("Stopped on failure");
	},
	
	fail: function () {
		console.log("Error: Failed");
		throw new Error("Stopped on failure");
	},
	almostEq: function (a, b, eps) {
	    eps = (eps === undefined) ? 1e-7 : eps;
	    if (isNaN(a) || isNaN(b) || (Math.abs(a - b) > eps)) {
	        console.log("Error: Values " + a + " and " + b + " are not almost equal");
	        throw new Error("Stopped on failure");
	    }
	},
	
	raises: function (fn, entity, data, err) {
		try {
			if (data && data instanceof Array) {
				fn.apply(entity, data);
			} else {
				fn.call(entity, data);
			}
			this.fail();
		} catch (e) {
			if (err) this.eq(e, err);
		}
	},
	
	objlen: function (o) {
		return Object.keys(o).length;
	},
	
	run: function () {
		var alltests = [];
		for (var i in this) {
			if (i.slice(0, 4) === "test") {
				if (typeof(this[i]) === 'function') {
					console.log("Running " + i + "...");
					var test = this[i];

					if (this.setup) this.setup();
					test.call(this);
					if (this.teardown) this.teardown();
	
				}
			}
		}
		console.log("SUCCESS!!");
	},
	
	dump: function (arr,level) {
	    var dumped_text = "";
	    if(!level) level = 0;

	    var level_padding = "";
	    for(var j=0;j<level+1;j++) level_padding += "    ";

	    if(typeof(arr) == 'object') {  
	        for(var item in arr) {
	            var value = arr[item];

	            if(typeof(value) == 'object') { 
	                dumped_text += level_padding + "'" + item + "' ...\n";
	                dumped_text += this.dump(value,level+1);
	            } else {
	                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	            }
	        }
	    } else { 
	        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	    }
	    return dumped_text;
	}
	
});